<?php

// *** Documentation
/*______________________________________________________________________________

  Bafflegate Site Metric Script
  Version 0.02
  
  Last Update: August 2007
  Author: Tom at klenwell@gmail.com
  
  SUMMARY
  a crude test
  
  NOTES
  to test, call directly: http://localhost/BAFFLEGATE/version0/log.m02.php?bafflekey=direct
		
______________________________________________________________________________*/


// *** Pre-Script (core settings, includes)
/*____________________________________________________________________________*/

// ** Meta Variables
	
  // timer
  $_tx1 = microtime();
  
  // syntax declarations
  define('DS', DIRECTORY_SEPARATOR);
  
  // pre-script events
  if ( ob_get_level() == 0 ) ob_start();
  session_start();
	

// ** Core Page Settings
#$_DIR['super'] = dirname($_SERVER['DOCUMENT_ROOT']) . DS;
$_DIR['root'] = '..' . DS;

	
// ** Includes
require_once('functions.m01.inc.php');
require_once($_DIR['root'] . 'oss/adodb_lite/adodb.inc.php');
	
/*============================================================================*/



// *** Data (triggers, flags, HTML, and other variables)
/*____________________________________________________________________________*/

// ** Controller Flags

  // the cue
  $cue = 'bafflekey';
  $test_table = 'log_m01';

  // Triggers (Page Events)
  $_TRIGGER['cx_baffler'] = 0;
  $_TRIGGER['log_visit'] = 0;
  $_TRIGGER['log_session'] = 0;
  $_TRIGGER['log_seo'] = 0; 
  $_TRIGGER['log_referrer'] = 0;
  $_TRIGGER['log_visitor'] = 0;


// ** Data
	

// ** Output


/*============================================================================*/



// *** Controllers (handles requests and sets event triggers)
/*____________________________________________________________________________*/

// GET Triggers
// this script will be called either from a javascript file or an img tag of 
// the page and thus should require some kind of GET value to trigger construction
// of the baffler object
if ( !empty($_GET[$cue]) )
{
  $_TRIGGER['cx_baffler'] = 1;
  $_TRIGGER['log_visit'] = 1;
}
else
{
  // can we assume that this is an error or an unwanted direct call to this file?
  $_TRIGGER['redirect'] = 1;
}

// debug
if ( 0 )
{
  echo '<script type="text/javascript">alert("'. $_SERVER['PHP_SELF'] . ' called")</script>';
  die();
}

/*============================================================================*/



// *** Events (trigger-controlled events)
/*____________________________________________________________________________*/

// construct object
if ( $_TRIGGER['cx_baffler'] )
{
  // create object
  #$Baffler = new Bafflegate();
  $Baffler = new stdClass();
  
  // get data
  #$Baffler->get_visitor_data();
  
  // site data
  $Baffler->baffle_key = $_GET[$cue];
  $Baffler->uts = time();
  $Baffler->visited_url = ( !empty($_SERVER['HTTP_REFERER']) ) ? $_SERVER['HTTP_REFERER'] : '';
  $Baffler->visited_qstring = 'tbd';
  $Baffler->visited_title = ( !empty($_GET['ttl']) ) ? urldecode($_GET['ttl']) : '';
  $Baffler->referrer = ( !empty($_GET['ref']) ) ? urldecode($_GET['ref']) : '';
  
  // visitor data
  $Baffler->client_ip = get_client_ip();
  $Baffler->hostname = 'tbd';
  $Baffler->proxy_ip = 'tbd';
  $Baffler->proxy = get_proxy();
  $Baffler->proxy_hostname = 'tbd';
  
  // agent data
  $Baffler->agent_string = $_SERVER['HTTP_USER_AGENT'];
  $Baffler->agent_hash = md5($Baffler->agent_string);
  $Baffler->js_enabled = ( isset($_GET['jsa']) ) ? $_GET['jsa'] : '-1';
  $Baffler->browser = 'tbd';
  $Baffler->browser_version = 'tbd';
  $Baffler->os = ( !empty($_GET['uos']) ) ? urldecode($_GET['uos']) : '';
  $Baffler->screen_size = ( !empty($_GET['ssz']) ) ? urldecode($_GET['ssz']) : '';
  $Baffler->screen_depth = ( !empty($_GET['sdp']) ) ? urldecode($_GET['sdp']) : '';
  
    // get proxy
    // client_ip = get_ip
    // hostname = @getHostByAddr($client_ip)
    // if proxy
       // proxy_ip = get_ip_simple else client_ip
       // proxy_hostname = @getHostByAddr($proxy_ip)
}

// log visit
if ( $_TRIGGER['log_visit'] ) 
{
  // log visit
  #$Baffler->log_visit();
    // apply filters -- my first impulse was to even logged filtered visitor (e.g.
      // a blacklisted ip address), but maybe safer just to ignore
      // would it be possible for script to serve as a bouncer using javascript?
      // well, bad guys probably won't have js enabled.  outside scope, anyway. 
    // get site id (referer?)
    // hit db
    // new session?  set log_session trigger
    
    // data bind
    $_INSERT = array
    (
      $Baffler->baffle_key,
      $Baffler->visited_url,
      $Baffler->visited_qstring,
      $Baffler->referrer,
      $Baffler->uts,
      $Baffler->client_ip,
      $Baffler->hostname,
      $Baffler->proxy,      
      $Baffler->proxy_ip,
      $Baffler->proxy_hostname,
      $Baffler->agent_string,
      $Baffler->agent_hash,
      $Baffler->js_enabled,
      $Baffler->browser,
      $Baffler->browser_version,
      $Baffler->os,
      $Baffler->screen_size,
      $Baffler->screen_depth,
    );
    
    // insert
    $_SQL['insert'] = <<<SQL
INSERT INTO $test_table
( baffle_key, url, query_string, referrer_url, uts, client_ip, 
  client_host, proxy, proxy_ip, proxy_host, agent_string, agent_hash, 
  js_enabled, browser, version, os, screen_size, screen_depth ) 
VALUES ( ?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,? )
SQL;

    // settings
    $db_user = 'root';
    $db_pass = 'root';
    $db_name = 'bafflegate';
    $db_server = 'localhost';
    
    // create object
    $_pw = urlencode($db_pass);
    $_flags = 2;
    $_dsn = "mysql://$db_user:$_pw@$db_server/$db_name?clientflags=$_flags";
    if ( !$DBO =& ADONewConnection($_dsn) ) 
    {
      trigger_error('unable to connect to database [' . $db_name . ']', E_USER_WARNING);
    }
    
    // run query
    if ( !$DBO_r = $DBO->Execute($_SQL['insert'], $_INSERT) )
    {
      trigger_error($DBO->ErrorMsg(), E_USER_WARNING);
      trigger_error($_SQL['insert']);
      print_r($Baffler);
      return 0;
    }
    else
    {
      $insert_id = $DBO->Insert_ID();
      echo "insert id: $insert_id";
    } 
}

// log session
if ( $_TRIGGER['log_session'] ) 
{
  // log session
  #$Baffler->log_session();
    // is filtered
    // hit db
    // new referral? set log_referrer
    // new search referral? set log_seo
    // new visitor? set log_visitor
}

// log referrer
if ( $_TRIGGER['log_referrer'] ) {}

// log seo
if ( $_TRIGGER['log_seo'] ) {}

// log visitor
if ( $_TRIGGER['log_visitor'] ) {}

/*============================================================================*/


// *** Output (handles requests and sets event triggers)
/*____________________________________________________________________________*/


/*============================================================================*/



// *** Post-Script (close HTML, flush buffer, and other backend operations)
/*____________________________________________________________________________*/

// ** Flush Buffer
while (ob_get_level() > 0) { ob_end_flush(); }
flush();
$_HTML['flush'] = "<!-- buffer flushed at " . date('r') . " -->";

// ** Page Timer
$_tx2 = microtime();
$_tx3 = number_format(((substr($_tx2,0,9)) + (substr($_tx2,-10)) - (substr($_tx1,0,9)) - (substr($_tx1,-10))),4); 
$_HTML['timer'] = "\n<!-- script [id: {$_PAGE['id']}] generated in $_tx3 s -->";

/*============================================================================*/
// * That's All Folks!
?>
